<template>
    <div style="height:100%;">
        <!-- 标题 -->
        <dv-border-box-11
            style="height:  50px;width: 450px;text-align: center; position: absolute;left: 50%; transform: translate(-50%,0); z-index:100; ">
            <div id="projectTitle">岩土GIS平台</div>
        </dv-border-box-11>
        <!-- 地图 -->
        <div id="cesiumContainer" style="height:100%"></div>
        <!-- home键 -->
        <div class="home-btn-style" @click="comeHome" style="left: 10px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/danwei.png" />
        </div>
        <!-- 二三维转换 -->
        <div class="home-btn-style" @click="check3D" style="left: 55px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/shuibeng.png" />
        </div>
        <!-- 地形加载 -->
        <div class="home-btn-style" @click="getTerrain" style="left: 100px; top: 10px;">
            <img class="icon-font" style="width: 20px; height: 20px;" src="../../public/iconfont/gis_dixing.png" />
        </div>
        <!-- 底图切换 -->
        <div class="home-btn-style" @click="checkBaseMap" style="left: 145px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/tongyongcaidandiejia.png" />
        </div>
        <!-- 日期 -->
        <div class="dateAndWeather">
            <div class="headerDate">{{ this.date }}</div>
        </div>
        <!-- 搜索 -->
        <div class="home-btn-style" @click="toThere" style="right: 300px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/sousuo.png" style="width: 20px; height: 20px;" />
        </div>
        <!-- 跳转飞机模型 -->
        <div class="home-btn-style" @click="toPlaneModel" style="right: 350px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/feiji.png" style="width: 20px; height: 20px;" />
        </div>
        <!-- 搜索框 -->
        <input type="text" name="search" class="search_box" v-model="searchValue" placeholder="输入地名自动跳转"
            placeholdercolor="white" />
        <!-- 保存位置 -->
        <div class="home-btn-style" @click="downloader" style="right: 10px; top: 10px;">
            <img class="icon-font" src="../../public/iconfont/baocun.png" style="width: 20px; height: 20px;" />
        </div>
        <!-- 底部信息栏 -->
        <div class="bottomInfo_box" style="right: 50%; bottom: 0px;">
            <div>{{ this.bottomData[0] }}</div>
            <div>{{ this.bottomData[1] }}</div>
            <div>{{ this.bottomData[2] }}</div>
            <div>{{ this.bottomData[3] }}</div>
            <div>{{ this.bottomData[4] }}</div>
            <div>{{ this.bottomData[5] }}</div>
            <div>{{ this.bottomData[6] }}</div>
        </div>
        <!-- 悬浮框 -->
        <div ref="labelRef"
            style="position:absolute; z-index: 110; width: 100px; height:100px; background-color: rgba(39, 52, 125, 0.7); border: 1px solid rgb(146, 171, 243); border-radius: 5px;">
            <div ref="labelRefId" style="position: absolute; left:5px; top:5px"></div>
            <div ref="labelRefName" style="position: absolute; left:5px; top:25px"></div>
        </div>
        <!-- 双击echarts -->
        <div id="echart_box" ref="entitiesBoxRef">
            <div id="echart" ref="echartRef"></div>
            <div ref="hiddenEntities" class="home-btn-style" @click="hiddenEntitiesBox"
                style="right: 5px; top: 5px; width: 20px; height:20px; border-radius: 5px; line-height: 20px;">X</div>
            <div ref="discripBoxRef"
                style="width: 700px; height: 400px; position: absolute; left: 50%; top: 10%;transform: translate(-50%, 0);">
            </div>
        </div>
        <!-- 剖面海拔echarts -->
        <div id="profile_box" ref="profileboxRef">
            <div id="profile"></div>
            <div ref="hiddenProfile" class="home-btn-style" @click="hiddenprofileBox"
                style="right: 5px; top: 5px; width: 20px; height:20px; border-radius: 5px; line-height: 20px;">X</div>
        </div>
        <!-- 测量工具栏 -->
        <div class="home-btn-style" @click="boxMove1" style="right: 10px; top: 100px; border-radius: 5px;">
            <img class="icon-font" src="../../public/iconfont/chizi_o.png" style="width: 20px; height: 20px;" />
        </div>
        <!-- 测量工具 -->
        <div ref="utilBox" class="util_box"
            style="width: 100px; height: 250px; right: 10px; top:160px; font-size: small; display: none;">
            <div @click="draw('PolylineSpace')" ref="lineMeasureRef2" style="margin-top: 5px;">空间直线测量</div>
            <div @click="draw('Polyline')" ref="lineMeasureRef">贴地直线测量</div>
            <div @click="draw('Polygon')" ref="polygonRef">空间面积测量</div>
            <div @click="draw('Angle')" ref="angleRef">空间角度测量</div>
            <div @click="draw('Profile')" ref="profileRef">地形剖面分析</div>
            <div @click="clearAllDrawn">清除测量数据</div>
        </div>
        <!-- 点位添加按钮 -->
        <div class="home-btn-style" @click="boxMove2" style="left: 10px; top: 100px; border-radius: 5px;">
            <img class="icon-font" src="../../public/iconfont/tianjiaguanggaowei.png" style="width: 20px; height: 20px;" />
        </div>
        <!-- 点位添加栏 -->
        <div class="addEntities_box" ref="addEntitiesBox">
            <div>名称:
                <input type="text" name="entityname" v-model="entitiesInfo.name" class="input_style" placeholder="输入该点位名称"
                    placeholdercolor="white" />
            </div>
            <div>经度:
                <input type="text" name="lon" v-model="entitiesInfo.position._value.x" class="input_style"
                    placeholder="输入该点位经度" placeholdercolor="white" />
            </div>
            <div>纬度:
                <input type="text" name="lat" v-model="entitiesInfo.position._value.y" class="input_style"
                    placeholder="输入该点位纬度" placeholdercolor="white" />
            </div>
            <div>高度:
                <input type="text" name="height" v-model="entitiesInfo.position._value.z" class="input_style"
                    placeholder="输入该点位高度" placeholdercolor="white" />
            </div>
            <div>描述:
                <input type="text" name="descript" v-model="entitiesInfo.description" class="input_style"
                    placeholder="输入该点位描述" placeholdercolor="white" />
            </div>
            <div>类型:
                <select class="input_style" v-model="entitiesInfo.type" style="width: 106px; height: 20px;" name="type"
                    placeholdercolor="white">
                    <option>描述点位</option>
                    <option>数据点位</option>
                    <option>钻孔点位</option>
                </select>
            </div>
            <div class="add_style" style="right: 5%;" @click="addEntities">输入添加</div>
            <div class="add_style" style="left: 5%;" ref="clickAddBtn" @click="addEntitiesByClick">点图添加</div>
        </div>
        <div></div>
        <!-- 点位管理按钮 -->
        <div class="home-btn-style" @click="boxMove3" style="right: 40%; top: 70px;  border-radius: 5px;">
            <img class="icon-font" src="../../public/iconfont/xunjian.png" />
        </div>
        <!-- 点位管理页面 -->
        <div class="entitiesInfoBox" ref="entitiesInfoBox">
            <div style="position: absolute; left:2.5%; top:2.5%; font-size: 20px; color: ;">全部点位信息</div>
            <el-table :data="entitiesArray.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                :header-cell-style="{ background: 'rgb(146, 171, 243)', color: 'white' }"
                style=" color: rgb(146, 171, 243);border: 1px solid rgb(146, 171, 243); width: 95%; height: 380px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); border-radius: 5px;">
                <el-table-column label="ID" width="110" style="background-color: transparent !important;">
                    <template slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column label="名称" width="150">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column label="经度" width="100">
                    <template slot-scope="scope">{{ scope.row.lon }}</template>
                </el-table-column>
                <el-table-column label="纬度" width="100">
                    <template slot-scope="scope">{{ scope.row.lat }}</template>
                </el-table-column>
                <el-table-column label="高度" width="100">
                    <template slot-scope="scope">{{ scope.row.height }}</template>
                </el-table-column>
                <el-table-column prop="description._value" label="简介">
                    <template slot-scope="scope">{{ scope.row.description }}</template>
                </el-table-column>
                <el-table-column label="操作" width="90">
                    <template slot-scope="scope">
                        <div class="tableUtilBtn" @click="updateThisRow(scope.$index, scope.row)">编辑</div>
                        <div class="tableUtilBtn" @click="removeThisRow(scope.$index, scope.row)">删除</div>
                    </template>

                </el-table-column>
            </el-table>
            <el-pagination layout="prev, pager, next" :total="entitiesArray.length" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-size="pageSize"
                style="position: absolute; bottom: 5px; left: 50%; transform: translate(-50%, 0);">
            </el-pagination>
            <div class="entitiesInfoBox" style="width: 300px; height:300px; display: none;" ref="updateBox">
                <div>名称:
                    <input type="text" name="entityname" v-model="entitiesInfo1.name" class="input_style"
                        placeholder="输入该点位名称" placeholdercolor="white" />
                </div>
                <div>经度:
                    <input type="text" name="lon" v-model="entitiesInfo1.position._value.x" class="input_style"
                        placeholder="输入该点位经度" placeholdercolor="white" />
                </div>
                <div>纬度:
                    <input type="text" name="lat" v-model="entitiesInfo1.position._value.y" class="input_style"
                        placeholder="输入该点位纬度" placeholdercolor="white" />
                </div>
                <div>高度:
                    <input type="text" name="height" v-model="entitiesInfo1.position._value.z" class="input_style"
                        placeholder="输入该点位高度" placeholdercolor="white" />
                </div>
                <div>描述:
                    <input type="text" name="descript" v-model="entitiesInfo1.description" class="input_style"
                        placeholder="输入该点位描述" placeholdercolor="white" />
                </div>
                <div>类型:
                    <select class="input_style" v-model="entitiesInfo1.type" style="width: 106px; height: 20px;" name="type"
                        placeholdercolor="white">
                        <option>描述点位</option>
                        <option>数据点位</option>
                        <option>钻孔点位</option>
                    </select>
                </div>
                <div class="add_style"
                    style="background-color: white; color:rgb(146, 171, 243); left: 50%; transform: translate(-50%,0);"
                    @click="updateEntities">
                    修改
                </div>
            </div>
        </div>
        <!-- 钻孔弹窗 -->
        <div class="home-btn-style" ref="drillholeRef"
            style="display: none; font-size: small; right: 20%; top: 40%;  border-radius: 5px; transform: translate(50%, 0); width:100px; height: 130px;">
            <div @click="removeAllHole">清除钻孔柱状图</div>
            <div @click="initAllHole">加载所有钻孔图</div>
            <div @click="quitDrilHole">退出地下图模式</div>
        </div>
        <!-- 淹没分析按钮 -->
        <div class="home-btn-style" @click="boxMove4" style="left: 40%; top: 70px;  border-radius: 5px;">
            <img class="icon-font" src="../../public/iconfont/shuiliuliang.png" style="width: 20px; height:20px;" />
        </div>
        <!-- 淹没分析设置栏 -->
        <div class="home-btn-style" ref="waterRef"
            style="display: none; font-size: small; left: 20%; top: 70px;  border-radius: 5px; transform: translate(50%, 0); width:180px; height: 220px;">
            <div>最高水位:
                <input type="text" name="entityname" v-model="maxWaterHeight" class="input_style" placeholder="输入最高水位"
                    placeholdercolor="white" />
            </div>
            <div>最低水位:
                <input type="text" name="entityname" v-model="minWaterHeight" class="input_style" placeholder="输入最低水位"
                    placeholdercolor="white" />
            </div>
            <div @click="draw('Water')" ref="darwWaterRef" class="darwWaterBtn">描绘淹没范围</div>
            <div @click="waterAnalysis(maxWaterHeight, waterArea, minWaterHeight)" class="darwWaterBtn" ref="waterComing">
                模拟场景</div>
            <div @click="resetWater" class="darwWaterBtn">重置</div>
        </div>
        <!-- 比例尺 -->
        <div class="scale">比例尺：{{ this.scale }}</div>
    </div>
</template>

<script>
export default {
    name: 'cesiumDemo',
    data() {
        return {
            viewer: null,
            date: '',
            /** 需输入个人天地图token */
            token: '',
            mapType: 'SL',
            tdtUrl: 'https://t{s}.tianditu.gov.cn/',
            terrainValue: true,
            searchValue: '',
            bottomData: [],
            entitiesData: [
                {
                    id: 1,
                    lon: 110,
                    lat: 50,
                    height: 1274
                }, {
                    id: 2,
                    lon: 110,
                    lat: 100,
                    height: 1274
                }, {
                    id: 3,
                    lon: 110,
                    lat: 150,
                    height: 1274
                }, {
                    id: 4,
                    lon: 110,
                    lat: 200,
                    height: 1274
                }, {
                    id: 5,
                    lon: 110,
                    lat: 250,
                    height: 1274
                }, {
                    id: 6,
                    lon: 110,
                    lat: 300,
                    height: 1274
                }, {
                    id: 7,
                    lon: 110,
                    lat: 350,
                    height: 1274
                }, {
                    id: 8,
                    lon: 110,
                    lat: 400,
                    height: 1274
                }, {
                    id: 9,
                    lon: 100,
                    lat: 150,
                    height: 1274
                }, {
                    id: 10,
                    lon: 150,
                    lat: 200,
                    height: 1274
                }, {
                    id: 11,
                    lon: 200,
                    lat: 250,
                    height: 1274
                }, {
                    id: 12,
                    lon: 250,
                    lat: 300,
                    height: 1274
                }, {
                    id: 13,
                    lon: 300,
                    lat: 300,
                    height: 1274
                }, {
                    id: 14,
                    lon: 350,
                    lat: 300,
                    height: 1274
                }, {
                    id: 15,
                    lon: 400,
                    lat: 300,
                    height: 1274
                }, {
                    id: 16,
                    lon: 450,
                    lat: 300,
                    height: 1274
                },],
            moveValue1: true,
            moveValue2: true,
            moveValue3: true,
            moveValue4: true,
            tempEntities: [],
            pointNum: 0,
            jieliuFlag: true,
            entitiesInfo: {
                name: '',
                position: {
                    _value: {
                        x: '',
                        y: '',
                        z: '',
                    }
                },
                description: '',
                type: '',
            },
            entitiesArray: [],
            currentPage: 1,
            pageSize: 4,
            entitiesCount: 0,
            entitiesInfo1: {
                name: '',
                position: {
                    _value: {
                        x: '',
                        y: '',
                        z: '',
                    }
                },
                description: '',
                type: '',
            },
            TSvalue: false,
            poumianArray1: [],
            poumianArray2: [],
            maxWaterHeight: 0,
            minWaterHeight: 0,
            waterArea: [],
            waterArray1: [],
            waterArray2: [],
            scale: '',
            moxing: true,
        }
    },
    methods: {
        //获取标准格式日期
        getFormalDate() {
            var date = new Date()
            var month = date.getMonth() + 1
            var day = date.getDay()
            var hour = date.getHours()
            var minutes = date.getMinutes()
            var seconds = date.getSeconds()
            month >= 0 && month <= 9 ? month = "0" + month : month
            day >= 0 && day <= 9 ? day = "0" + day : day
            hour >= 0 && hour <= 9 ? hour = "0" + hour : hour
            minutes >= 0 && minutes <= 9 ? minutes = "0" + minutes : minutes
            seconds >= 0 && seconds <= 9 ? seconds = "0" + seconds : seconds

            var currentdate = date.getFullYear() + "年" + month + "月" + day
                + "日" + hour + ":" + minutes
                + ":" + seconds
            return currentdate
        },
        //回到中国
        comeHome() {
            this.viewer.camera.flyTo({
                destination: this.Cesium.Cartesian3.fromDegrees(110, 30, 4000000.0)
            })
        },
        //二三维转换
        check3D() {
            let viewer = this.viewer
            let Cesium = this.Cesium
            var limit
            this.TSvalue = !this.TSvalue
            if (this.TSvalue) {
                this.viewer.scene.morphTo2D(1)
                this.comeHome()
                viewer.scene.screenSpaceCameraController.maximumZoomDistance = 5000000;
                viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10;
                //实时监测镜头范围(该方法会一直调用)
                limit = setInterval(() => {
                    if (this.TSvalue == false) {
                        // console.log("已清除定时器limit")
                        clearInterval(limit)
                    }
                    var pt1 = new this.Cesium.Cartesian2(0, 0);
                    var pt2 = new this.Cesium.Cartesian2(500, 500);
                    var pt3 = new this.Cesium.Cartesian2(500, 0);
                    var pt4 = new this.Cesium.Cartesian2(0, 500);

                    var pick1 = viewer.scene.globe.pick(
                        viewer.camera.getPickRay(pt1),
                        viewer.scene
                    );
                    var pick2 = viewer.scene.globe.pick(
                        viewer.camera.getPickRay(pt2),
                        viewer.scene
                    );
                    var pick3 = viewer.scene.globe.pick(
                        viewer.camera.getPickRay(pt3),
                        viewer.scene
                    );
                    var pick4 = viewer.scene.globe.pick(
                        viewer.camera.getPickRay(pt4),
                        viewer.scene
                    );

                    //将三维坐标转成地理坐标
                    var geoPt1 = viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        pick1
                    );
                    var geoPt2 = viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        pick2
                    );
                    var geoPt3 = viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        pick3
                    );
                    var geoPt4 = viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        pick4
                    );

                    // //地理坐标转换为经纬度坐标
                    var point1 = [
                        (geoPt1.longitude / Math.PI) * 180,
                        (geoPt1.latitude / Math.PI) * 180
                    ];
                    var point2 = [
                        (geoPt2.longitude / Math.PI) * 180,
                        (geoPt2.latitude / Math.PI) * 180
                    ];
                    var point3 = [
                        (geoPt3.longitude / Math.PI) * 180,
                        (geoPt3.latitude / Math.PI) * 180
                    ];
                    var point4 = [
                        (geoPt4.longitude / Math.PI) * 180,
                        (geoPt4.latitude / Math.PI) * 180
                    ];
                    if (
                        point1[0] < 73 ||
                        point1[1] > 53 ||
                        point2[0] > 130 ||
                        point2[1] < 3 ||
                        point3[0] > 130 ||
                        point3[1] > 53 ||
                        point4[0] < 73 ||
                        point4[1] < 3
                    ) {
                        this.comeHome();
                    }

                }, 2000)
            } else {
                // console.log(this.TSvalue)
                viewer.scene.screenSpaceCameraController.maximumZoomDistance = 5000000;
                viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10;
                var china1
                //实时监测镜头范围(该方法会一直调用)
                china1 = setInterval(() => {
                    if (this.TSvalue == true) {
                        // console.log("已清除定时器china1")
                        clearInterval(china1)
                    }
                    //计算镜头范围方法，该方法会计算当前镜头地理坐标（弧度）范围并返回west,east,north,south 4个范围参数
                    let rectangle = viewer.camera.computeViewRectangle();
                    // console.log(rectangle,'rectangle');
                    //设置可浏览经纬度范围
                    let Range = { west: 72, north: 53, east: 150, south: 3.58 };
                    //地理坐标（弧度）转经纬度坐标
                    // 弧度转为经纬度，west为左（西）侧边界的经度，以下类推
                    let west = rectangle.west / Math.PI * 180;
                    let north = rectangle.north / Math.PI * 180;
                    let east = rectangle.east / Math.PI * 180;
                    let south = rectangle.south / Math.PI * 180;
                    //如果视角超出设置范围则跳转视角
                    if (west < Range.west || north > Range.north || east > Range.east || south < Range.south) {
                        // console.log("跳转视角");
                        this.viewer.camera.flyTo({
                            destination: this.Cesium.Cartesian3.fromDegrees(110, 30, 4000000.0)
                        })
                    }
                }, 3000)
                this.viewer.scene.morphTo3D(1)
            }
        },
        //获取地形
        getTerrain() {
            if (this.terrainValue) {
                var subdomains = ['0', '1', '2', '3', '4', '5', '6', '7'];
                // // 叠加国界服务
                // var iboMap = new this.Cesium.UrlTemplateImageryProvider({
                //     url: this.tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + this.token,
                //     subdomains: subdomains,
                //     maximumLevel: 10
                // });
                // this.viewer.imageryLayers.addImageryProvider(iboMap);
                // 叠加地形服务
                const loading = this.$loading({
                    lock: true,
                    text: '正在加载地形.......',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                setTimeout(() => {
                    var terrainProvider = new this.Cesium.CesiumTerrainProvider({
                        url: this.Cesium.IonResource.fromAssetId(1),
                        requestVertexNormals: true,
                        requestWaterMask: true
                    })
                    this.viewer.terrainProvider = terrainProvider
                });
                setTimeout(() => {
                    loading.close();
                }, 3000)


                this.terrainValue = false
            } else {
                // this.viewer.imageryLayers.removeAll()
                // this.viewer.imageryLayers.addImageryProvider(this.TDT_YX)
                this.viewer.terrainProvider = new this.Cesium.EllipsoidTerrainProvider({})
                this.terrainValue = true
            }
        },
        //初始化
        init() {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
                loading.close();
            }, 1000);
            //天地图影像
            this.TDT_YX = new this.Cesium.WebMapTileServiceImageryProvider({
                url: 'http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=' + this.token,
                layer: 'img',
                style: 'default',
                format: 'tiles',
                tileMatrixSetID: 'w',
                subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                credit: new this.Cesium.Credit('天地图影像'),
                maximumLevel: 18
            })

            //天地图地形
            // this.TDT_DX = new this.Cesium.WebMapTileServiceImageryProvider({
            //     url: 'http://{s}.tianditu.gov.cn/ter_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=' + this.token,
            //     layer: '111',
            //     style: 'default',
            //     format: '111',
            //     tileMatrixSetID: '11',
            //     subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
            //     credit: new this.Cesium.Credit('天地图地形'),
            //     maximumLevel: 18
            // })



            this.Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjMjU2ODkzYi04NDEyLTQ3ZTAtOTg5ZS1jODliNzIwNTlkNTEiLCJpZCI6MTE3ODcxLCJpYXQiOjE2NzA2MzU0OTZ9.VnGS40S30WOuZNiv8qB7z3Rt38PWZgsDmqh0jySnjt8';

            this.viewer = new this.Cesium.Viewer('cesiumContainer', {
                geocoder: false,
                homeButton: false,
                sceneModePicker: false,
                baseLayerPicker: false,
                navigationHelpButton: false,
                animation: false,
                timeline: false,
                fullscreenButton: false,
                vrButton: false,
                imageryProvider: this.TDT_YX
            });

            //设置初始视图位置
            let position = localStorage.getItem('position')

            //如有保存则为保存位置
            if (position != null) {
                var initpositionList = position.split(',')
                this.viewer.camera.setView({
                    destination: this.Cesium.Cartesian3.fromDegrees(Number(initpositionList[1]), Number(initpositionList[0]), Number(initpositionList[2])),
                });
            }
            setInterval(() => {
                this.date = this.getFormalDate()
            }, 1000)

            let viewer = this.viewer
            let Cesium = this.Cesium
            viewer.scene.screenSpaceCameraController.maximumZoomDistance = 5000000;
            viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10;
            var china
            //实时监测镜头范围(该方法会一直调用)
            china = setInterval(() => {
                if (this.TSvalue == true) {
                    clearInterval(china)
                }
                //计算镜头范围方法，该方法会计算当前镜头地理坐标（弧度）范围并返回west,east,north,south 4个范围参数
                let rectangle = viewer.camera.computeViewRectangle();
                // console.log(rectangle,'rectangle');
                //设置可浏览经纬度范围
                let Range = { west: 72, north: 53, east: 150, south: 3.58 };
                //地理坐标（弧度）转经纬度坐标
                // 弧度转为经纬度，west为左（西）侧边界的经度，以下类推
                let west = rectangle.west / Math.PI * 180;
                let north = rectangle.north / Math.PI * 180;
                let east = rectangle.east / Math.PI * 180;
                let south = rectangle.south / Math.PI * 180;
                //如果视角超出设置范围则跳转视角
                if (west < Range.west || north > Range.north || east > Range.east || south < Range.south) {
                    // console.log("跳转视角");
                    this.viewer.camera.flyTo({
                        destination: this.Cesium.Cartesian3.fromDegrees(110, 30, 4000000.0)
                    })
                }
            }, 3000)
        },
        //更换底图
        checkBaseMap() {
            this.viewer.imageryLayers.removeAll()
            switch (this.mapType) {
                case 'YX': {
                    this.viewer.imageryLayers.addImageryProvider(this.TDT_YX)
                    this.mapType = 'SL'
                    break
                }
                case 'SL': {
                    //天地图矢量
                    this.TDT_SL = new this.Cesium.WebMapTileServiceImageryProvider({
                        url: 'http://{s}.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=' + this.token,
                        layer: 'vec',
                        style: 'default',
                        format: 'tiles',
                        tileMatrixSetID: 'w',
                        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                        credit: new this.Cesium.Credit('天地图矢量'),
                        maximumLevel: 18
                    })
                    this.viewer.imageryLayers.addImageryProvider(this.TDT_SL)
                    this.mapType = 'YX'
                    break
                }
                // case 'DX': {
                //     this.viewer.imageryLayers.addImageryProvider(this.TDT_DX)
                //     this.mapType = 'YX'
                //     break
                // }
            }
        },
        //保存当前位置
        downloader() {
            var position = this.viewer.scene.camera.positionCartographic
            //弧度转化经纬度
            var longitude = this.Cesium.Math.toDegrees(position.longitude).toFixed(6)
            var latitude = this.Cesium.Math.toDegrees(position.latitude).toFixed(6)
            var positionList = [latitude, longitude, position.height]
            alert('保存位置成功')
            localStorage.setItem('position', positionList)
        },
        //镜头飞行到搜索位置
        async toThere() {
            // console.log(this.searchValue)
            if (this.searchValue === '') {
                alert('请输入位置！')
            } else {
                await this.$axios.get(`http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"${this.searchValue}"}&tk=${this.token}`)
                    .then(res => {
                        // console.log(res)
                        if (res.data === undefined) {
                            alert('无法获取' + this.searchValue + '地理位置！');
                        } else {
                            this.viewer.camera.flyTo({
                                destination: this.Cesium.Cartesian3.fromDegrees(res.data.location.lon, res.data.location.lat, 40000),
                            });
                        }
                    })
            }
        },
        //高度转换
        heightToZoom(height) {
            var A = 40487.57;
            var B = 0.00007096758;
            var C = 91610.74;
            var D = -40467.74;
            return Math.round(D + (A - D) / (1 + Math.pow(height / C, B)));
        },
        //下方的信息栏
        mouseMoveInfo() {
            this.getScale()
            var handler3D = new this.Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
            handler3D.setInputAction((movement) => {
                var pick = new this.Cesium.Cartesian2(movement.endPosition.x, movement.endPosition.y);
                // console.log(pick)
                if (pick) {
                    // console.log(this.viewer.scene)
                    var cartesian = this.viewer.scene.globe.pick(this.viewer.camera.getPickRay(pick), this.viewer.scene);
                    if (cartesian) {
                        //世界坐标转地理坐标（弧度）
                        var cartographic = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
                        // console.log(cartesian)
                        if (cartographic) {
                            //海拔
                            var height = this.viewer.scene.globe.getHeight(cartographic);
                            // console.log(height)
                            //视角海拔高度
                            var he = Math.sqrt(this.viewer.scene.camera.positionWC.x * this.viewer.scene.camera.positionWC.x + this.viewer.scene.camera.positionWC.y * this.viewer.scene.camera.positionWC.y + this.viewer.scene.camera.positionWC.z * this.viewer.scene.camera.positionWC.z);
                            var he2 = Math.sqrt(cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z);
                            //地理坐标（弧度）转经纬度坐标
                            var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];
                            if (!height) {
                                height = 0;
                            }
                            if (!he) {
                                he = 0;
                            }
                            if (!he2) {
                                he2 = 0;
                            }
                            if (!point) {
                                point = [0, 0];
                            }
                            var heightZoom = Math.ceil(this.viewer.camera.positionCartographic.height);
                            var zoom = this.heightToZoom(heightZoom);
                            this.bottomData[0] = '纬度：' + point[1].toFixed(6)
                            this.bottomData[1] = '经度：' + point[0].toFixed(6)
                            this.bottomData[2] = '横：' + cartesian.x
                            this.bottomData[3] = '纵：' + cartesian.y
                            this.bottomData[4] = '海拔：' + height + '米'
                            this.bottomData[5] = '层级：' + zoom
                            this.bottomData[6] = '视高：' + (he - he2).toFixed(2) + '米'
                        }
                    }
                }
            }, this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        },
        //比例尺
        getScale() {
            let viewer = this.viewer
            let Cesium = this.Cesium
            // 测算比例尺
            viewer.scene.postRender.addEventListener(() => {
                // 测算方法
                let scene = viewer.scene;
                let width = scene.canvas.clientWidth;
                let height = scene.canvas.clientHeight;
                // let ray= viewer.camera.getPickRay(new this.Cesium.Cartesian2((width / 2) | 0, height - 1));
                let left = scene.camera.getPickRay(
                    new this.Cesium.Cartesian2((width / 2) | 0, height - 1)
                );
                let right = scene.camera.getPickRay(
                    new this.Cesium.Cartesian2((1 + width / 2) | 0, height - 1)
                );
                // let globe = scene.globe;
                let leftPosition = viewer.scene.globe.pick(left, viewer.scene);
                let rightPosition = viewer.scene.globe.pick(right, scene);
                // console.log(rightPosition)
                let geodesic = new this.Cesium.EllipsoidGeodesic();
                if (leftPosition) {
                    let leftCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(leftPosition);
                    let rightCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(rightPosition);
                    geodesic.setEndPoints(leftCartographic, rightCartographic);
                    let pixelDistance = geodesic.surfaceDistance;
                    this.scale = pixelDistance * 1000 > 1000 ? Math.floor(pixelDistance / 10) + 'km' : Math.floor(pixelDistance * 1000) + 'm'
                    // console.log(pixelDistance);
                }
            })
        },
        //鼠标悬浮显示实体模型信息
        entitiesMask() {
            var handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
            handler.setInputAction((movement) => {

                if (this.viewer.scene.mode !== this.Cesium.SceneMode.MORPHING) {
                    var pickedObject = this.viewer.scene.pick(movement.endPosition);
                    if (this.viewer.scene.pickPositionSupported && this.Cesium.defined(pickedObject) && pickedObject.id !== '') {
                        var cartesian = this.viewer.scene.pickPosition(movement.endPosition);
                        if (this.Cesium.defined(cartesian)) {
                            if (pickedObject.id._name != '测量点') {
                                if (pickedObject.id._description._value.substr(2, 2) == '点位') {
                                    let cartesian2 = this.Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, cartesian);
                                    this.$refs.labelRef.style.display = 'block'
                                    this.$refs.labelRef.style.top = cartesian2.y + 'px'
                                    this.$refs.labelRef.style.left = cartesian2.x + 5 + 'px'
                                    this.$refs.labelRefId.innerHTML = 'id:' + pickedObject.id._id
                                    this.$refs.labelRefName.innerHTML = 'name:' + pickedObject.id._name
                                }
                            }
                        } else {
                            this.$refs.labelRef.style.display = 'none'
                        }
                    } else {
                        this.$refs.labelRef.style.display = 'none'
                    }
                }

            }, this.Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        },
        //镜头飞行到飞机位置
        toPlaneModel() {
            //加载飞机和建筑模型
            if (this.moxing) {
                this.moxing = false
                var gltf = this.viewer.entities.add({
                    id: 'building',
                    name: '这是一个建筑模型',
                    description: "描述点位",
                    position: new this.Cesium.Cartesian3.fromDegrees(103.90102, 31.07595, 0),
                    model: {
                        uri: 'static/BIM模型.gltf',
                        scale: 0.1
                    }
                })

                var gltf = this.viewer.entities.add({
                    id: 'plane',
                    name: '这是一个飞机模型',
                    description: "数据点位",
                    position: new this.Cesium.Cartesian3.fromDegrees(103.90102, 31.07595, 10000),
                    model: {
                        uri: 'static/WoodTower/CesiumAir/Cesium_Air.glb',
                        scale: 100
                    }
                })

                const pinBuilder = new this.Cesium.PinBuilder()
                let planeEntity = this.viewer.entities.add({
                    id: 'planelocal',
                    name: '飞机的位置',
                    description: '描述点位',
                    position: this.Cesium.Cartesian3.fromDegrees(103.90102, 31.07595, 10000),
                    billboard: {
                        image: pinBuilder.fromText("飞机", this.Cesium.Color.RED, 48).toDataURL(),
                        verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
                    },
                    label: {
                        show: false,
                        showBackground: true,
                        font: '14px monospace',
                        horizontalOrigin: this.Cesium.HorizontalOrigin.LEFT,
                        verticalOrigin: this.Cesium.VerticalOrigin.TOP,
                        pixelOffset: new this.Cesium.Cartesian2(15, 0)
                    }
                })

                let buildingEntity = this.viewer.entities.add({
                    id: 'buildinglocal',
                    name: '建筑的位置',
                    description: '描述点位，这是对该物体的一段描述，这是一个用于模拟实际业务场景的建筑模型',
                    position: this.Cesium.Cartesian3.fromDegrees(103.90102, 31.00595, 0),
                    billboard: {
                        image: pinBuilder.fromText("建筑", this.Cesium.Color.BLUE, 48).toDataURL(),
                        verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
                    },
                    label: {
                        show: false,
                        showBackground: true,
                        font: '14px monospace',
                        horizontalOrigin: this.Cesium.HorizontalOrigin.LEFT,
                        verticalOrigin: this.Cesium.VerticalOrigin.TOP,
                        pixelOffset: new this.Cesium.Cartesian2(15, 0)
                    }
                })
            }

            this.viewer.camera.flyTo({
                destination: this.Cesium.Cartesian3.fromDegrees(103.90102, 31.07595, 16000)
            })
        },
        //表格初始化
        initEchart() {
            let myEchart = this.$echarts.init(document.getElementById("echart"))
            let option = {
                color: ["rgb(174,232,210)", "rgb(86,109,203)", "rgb(192,213,251)"],
                legend: {
                    data: ["当日数量", "抽烟当日数量", "行为告警当日总数"],
                    textStyle: { fontSize: 16, color: '#fff' },
                    icon: 'roundRect',
                    bottom: 0,
                    itemWidth: 15,
                    itemHeight: 15
                },
                dataZoom: [
                    {
                        show: true,
                        type: 'inside',
                        start: 20,
                    },
                ],
                xAxis: {
                    data: ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                            color: "rgb(255,255,255)",
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            width: 2,
                        }
                    },
                    scale: true,
                    axisLabel: {//修改坐标系字体颜色
                        show: true,
                        textStyle: {
                            color: "#fff"
                        }
                    },

                },
                yAxis: {
                    interval: 100,
                    max: 300,
                    splitLine: {
                        lineStyle: {
                            color: "rgb(255,255,255)",
                            width: 2,
                        }
                    },
                    type: "value",
                    splitNumber: 2,
                    axisLabel: {//修改坐标系字体颜色
                        show: true,
                        textStyle: {
                            color: "#fff"
                        }
                    },

                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'line'
                    },
                },
                series: [
                    {
                        data: [60, 80, 100, 120, 200, 170, 180, 190, 220, 190, 178, 135],
                        type: 'line',
                        name: "当日数量",
                        smooth: true,
                        symbol: 'none',
                        lineStyle: {
                            width: 5
                        }
                    },
                    {
                        data: [100, 180, 160, 120, 200, 170, 160, 90, 180, 200, 178, 165],
                        type: 'line',
                        name: "抽烟当日数量",
                        smooth: true,
                        symbol: 'none',
                        lineStyle: {
                            width: 5
                        }
                    },
                    {
                        data: [180, 160, 140, 120, 100, 80, 100, 130, 150, 190, 178, 185],
                        type: 'line',
                        name: "行为告警当日总数",
                        smooth: true,
                        symbol: 'none',
                        lineStyle: {
                            width: 5
                        }
                    },
                ]
            }
            myEchart.setOption(option)
        },
        //隐藏双击信息栏
        hiddenEntitiesBox() {
            this.$refs.entitiesBoxRef.style.display = 'none'
            this.$refs.echartRef.style.display = 'none'
            this.$refs.hiddenEntities.style.display = 'none'
            this.$refs.discripBoxRef.style.display = 'none'
        },
        //隐藏剖面分析表
        hiddenprofileBox() {
            this.$refs.profileboxRef.style.display = 'none'
        },
        //双击实体模型显示信息栏
        entitiesDoubleClick() {
            var handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
            handler.setInputAction((click) => {
                if (this.viewer.scene.mode !== this.Cesium.SceneMode.MORPHING) {
                    var pickedObject = this.viewer.scene.pick(click.position);
                    if (pickedObject) {
                        if (pickedObject.id._description._value) {
                            if (pickedObject.id._description._value.substr(0, 2) == '数据') {
                                this.initEchart()
                                this.$refs.entitiesBoxRef.style.display = 'block'
                                this.$refs.echartRef.style.display = 'block'
                                this.$refs.hiddenEntities.style.display = 'block'
                            } else if (pickedObject.id._description._value.substr(0, 2) == '描述') {
                                this.$refs.entitiesBoxRef.style.display = 'block'
                                this.$refs.discripBoxRef.style.display = 'block'
                                // console.log(pickedObject.id)
                                this.$refs.discripBoxRef.innerHTML = pickedObject.id._description
                                this.$refs.hiddenEntities.style.display = 'block'
                            } else if (pickedObject.id._description._value.substr(0, 2) == '钻孔') {
                                // console.log(pickedObject.id._position._value)
                                // let category = this.Cesium.Cartographic.fromCartesian(pickedObject.id._position._value)
                                // let lon = this.Cesium.Math.toDegrees(category.longitude)
                                // let lat = this.Cesium.Math.toDegrees(category.latitude)
                                // let height = this.Cesium.Math.toDegrees(category.height)
                                this.entitiesArray.forEach(item => {
                                    if (pickedObject.id._id == item.id) {
                                        let lon = item.lon
                                        let lat = item.lat
                                        let height = item.height
                                        this.viewer.scene.globe.translucency.enabled = true
                                        this.viewer.scene.globe.translucency.frontFaceAlpha = 0.3
                                        this.drawHole(lon, lat, height)
                                        this.$refs.drillholeRef.style.display = 'block'
                                    }
                                })
                            }
                        }
                    }
                }
            }, this.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        },
        //加载全部钻孔点位柱状图
        initAllHole() {
            let viewer = this.viewer
            this.tempEntities = []
            let entitiesList = this.entitiesArray
            let rectangle = viewer.camera.computeViewRectangle();

            // 弧度转为经纬度，west为左（西）侧边界的经度，以下类推
            let west = rectangle.west / Math.PI * 180;
            let north = rectangle.north / Math.PI * 180;
            let east = rectangle.east / Math.PI * 180;
            let south = rectangle.south / Math.PI * 180;

            this.removeAllHole()
            entitiesList.forEach((item) => {
                if (item.type == '钻孔点位') {
                    let lon = item.lon
                    let lat = item.lat
                    let height = item.height
                    if (lon > west && lon < east && lat > south && lat < north) {
                        this.drawHole(lon, lat, height)
                    }
                }
            })
        },
        //画钻孔柱状图
        drawHole(lon, lat, height) {
            this.viewer.entities.add({
                name: "测量点",
                description: "柱状图",
                position: new this.Cesium.Cartesian3.fromDegrees(lon * 1, lat * 1, height * 1 - 3), // 点的经纬度坐标
                cylinder: {
                    length: 3,
                    topRadius: 0.5,
                    bottomRadius: 0.5,
                    material: this.Cesium.Color.fromBytes(192, 184, 28),
                },
            })
            this.viewer.entities.add({
                name: "测量点",
                description: "柱状图",
                position: new this.Cesium.Cartesian3.fromDegrees(lon * 1, lat * 1, height * 1 - 6), // 点的经纬度坐标
                cylinder: {
                    length: 3,
                    topRadius: 0.5,
                    bottomRadius: 0.5,
                    material: this.Cesium.Color.fromBytes(164, 101, 14),
                },
            })
            this.viewer.entities.add({
                name: "测量点",
                description: "柱状图",
                position: new this.Cesium.Cartesian3.fromDegrees(lon * 1, lat * 1, height * 1 - 9), // 点的经纬度坐标
                cylinder: {
                    length: 3,
                    topRadius: 0.5,
                    bottomRadius: 0.5,
                    material: this.Cesium.Color.BLUE,
                },
            })
            this.viewer.entities.add({
                name: "测量点",
                description: "柱状图",
                position: new this.Cesium.Cartesian3.fromDegrees(lon * 1, lat * 1, height * 1 - 12), // 点的经纬度坐标
                cylinder: {
                    length: 3,
                    topRadius: 0.5,
                    bottomRadius: 0.5,
                    material: this.Cesium.Color.fromBytes(99, 91, 80),
                },
            })
        },
        //清除钻孔柱状图
        removeAllHole() {
            let viewer = this.viewer
            this.tempEntities = []
            let entitiesList = viewer.entities._entities._array
            for (let index = 0; index < 10; index++) {
                entitiesList.forEach((item) => {
                    if (item.description == '柱状图') {
                        viewer.entities.remove(viewer.entities.getById(item.id))
                        // console.log('移除了' + item.name)
                    }
                })
            }
        },
        //退出地下图模式
        quitDrilHole() {
            this.removeAllHole()
            this.viewer.scene.globe.translucency.enabled = false
            this.$refs.drillholeRef.style.display = 'none'
        },
        //初始化实体模型和点位
        initEntities() {
            this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(this.Cesium.ScreenSpaceEventType.LEFT_CLICK)
            this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(this.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
            this.entitiesMask()
            this.entitiesDoubleClick()
            //加载标注点位
            // this.entitiesData.forEach(item => {
            // this.viewer.entities.add({
            //     id: item.id,
            //     position: this.Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height),
            //     point: {
            //         pixelSize: 10,
            //         color: this.Cesium.Color.RED,
            //     }
            // })
            // })

            /*//创建参数实例
            const dataForshow = new this.Cesium.CustomDataSource("dataForshow")

            this.viewer.dataSources.add(dataForshow).then((dataForshow) => {
                dataForshow.clustering.enabled = true
                //聚合范围
                dataForshow.clustering.pixelRange = 50
                dataForshow.clustering.minimumClusterSize = 5
                dataForshow.clustering.clusterEvent.addEventListener(
                    (clusteredEntities, cluster) => {
                        // console.log(cluster)
                        cluster.label.show = true
                        cluster.billboard.show = true
                        // 聚合时候的图片
                        if (clusteredEntities.length >= 10) {
                            cluster.billboard.image = 'static/iconfont/sousuo.png'
                            cluster.billboard.width = 50
                            cluster.billboard.height = 50
                        }
                        else if (clusteredEntities.length >= 5) {
                            cluster.billboard.image = 'static/iconfont/shuibeng.png'
                            cluster.billboard.width = 50
                            cluster.billboard.height = 50
                        }
                    }
                )
            })
            const clusterPoints = this.entitiesData
            clusterPoints.forEach((item) => {
                const entity = {
                    id: item.id,
                    position: this.Cesium.Cartesian3.fromDegrees(
                        item.lon,
                        item.lat,
                        item.height
                    ),
                    point: {
                        pixelSize: 10,
                        // color: this.Cesium.Color.RED
                    },
                    label: {
                        text: item.id + '',
                        show: false,
                        eyeOffset: new this.Cesium.Cartesian3(300000.0, 100000.0, 100000.0)
                    }
                }
                dataForshow.entities.add(entity)
            })*/
        },
        //盒子移动
        boxMove1() {
            if (this.moveValue1 === true) {
                this.$refs.utilBox.style.display = 'block'
                this.moveValue1 = false
            }
            else if (this.moveValue1 == false) {
                this.moveValue1 = true
                this.$refs.utilBox.style.display = 'none'
            }
        },
        boxMove2() {
            if (this.moveValue2 === true) {
                this.$refs.addEntitiesBox.style.display = 'block'
                this.moveValue2 = false
            }
            else if (this.moveValue2 == false) {
                this.moveValue2 = true
                this.$refs.addEntitiesBox.style.display = 'none'
            }
        },
        boxMove3() {
            if (this.moveValue3 === true) {
                this.$refs.entitiesInfoBox.style.display = 'block'
                this.moveValue3 = false
            }
            else if (this.moveValue3 == false) {
                this.moveValue3 = true
                this.$refs.entitiesInfoBox.style.display = 'none'
                // this.$refs.updateBox.style.display = 'none'
            }
        },
        boxMove4() {
            if (this.moveValue4 === true) {
                this.$refs.waterRef.style.display = 'block'
                this.moveValue4 = false
            }
            else if (this.moveValue4 == false) {
                this.moveValue4 = true
                this.$refs.waterRef.style.display = 'none'
                // this.$refs.updateBox.style.display = 'none'
            }
        },
        //空间距离的计算
        getSpaceLength(firstPoint, secondPoint) {
            // let distance = Math.sqrt(Math.pow(firstPoint.z - secondPoint.z, 2) + Math.pow(secondPoint.y - firstPoint.y, 2) + Math.pow(secondPoint.x - firstPoint.x, 2)) / 1000
            // return (distance).toFixed(2)
            let distance = this.Cesium.Cartesian3.distance(firstPoint, secondPoint)
            return (distance / 1000).toFixed(2)
        },
        /* 空间两点表面距离计算函数 */
        getLength(start, end) {
            // 将起点与终点位置信息从笛卡尔坐标形式转换为Cartographic形式
            let startCartographic = this.Cesium.Cartographic.fromCartesian(start)
            let endCartographic = this.Cesium.Cartographic.fromCartesian(end)
            // 初始化测地线
            let geodesic = new this.Cesium.EllipsoidGeodesic()
            // 设置测地线起点和终点，EllipsoidGeodesic中setEndPoints常与surfaceDistance搭配使用
            geodesic.setEndPoints(startCartographic, endCartographic)
            // 获取起点和终点之间的表面距离，单位为km，规定四舍五入保留两位小数
            // surfaceDistance返回number 单位为m，带小数
            // console.log((geodesic.surfaceDistance / 1000).toFixed(2))
            return (geodesic.surfaceDistance / 1000).toFixed(2)
        },
        getSpaceMidpoint(firstPoint, secondPoint) {
            let x = Math.abs(firstPoint.x - secondPoint.x)
            let y = Math.abs(firstPoint.y - secondPoint.y)
            let z = Math.abs(firstPoint.z - secondPoint.z)
            const position = new this.Cesium.Cartesian3(x, y, z);
            return position;
        },
        /* 空间两点计算贴地中点函数 */
        getMidpoint(start, end) {
            let Cesium = this.Cesium
            let startPoint = Cesium.Cartographic.fromCartesian(start)
            let endPoint = Cesium.Cartographic.fromCartesian(end)
            let geodesic = new Cesium.EllipsoidGeodesic()
            geodesic.setEndPoints(startPoint, endPoint)
            let geoPoint = geodesic.interpolateUsingFraction(0.5)
            // console.log(Cesium.Ellipsoid.WGS84.cartographicToCartesian(geoPoint))
            return Cesium.Ellipsoid.WGS84.cartographicToCartesian(geoPoint)
        },
        /* 在线段中点处添加标签，显示长度 */
        addLabel(midPoint, labelLength) {
            let viewer = this.viewer
            let Cesium = this.Cesium
            return viewer.entities.add({
                name: '测量点',
                position: midPoint,
                label: {
                    text: labelLength + 'km',
                    font: '20px sans-serif',
                    fillColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    backgroundColor: Cesium.Color.BLACK,
                    showBackground: true,
                    style: Cesium.LabelStyle.FILL,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
            })
        },
        //画点
        drawPoint(position) {
            let viewer = this.viewer
            // 本质上就是添加一个点的实体
            viewer.entities.add({
                name: '测量点',
                position: position,
                point: {
                    color: this.Cesium.Color.WHEAT,
                    pixelSize: 5,
                    outlineWidth: 3,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    heightReference: this.Cesium.HeightReference.CLAMP_TO_GROUND // 规定贴地
                }
            })
        },
        //画线
        drawPolyline(positions) {
            let viewer = this.viewer
            if (positions.length < 1) return
            viewer.entities.add({
                name: '测量点',
                polyline: {
                    positions: positions,
                    width: 5.0,
                    material: new this.Cesium.PolylineGlowMaterialProperty({
                        // eslint-disable-next-line new-cap
                        color: this.Cesium.Color.WHEAT
                    }),
                    depthFailMaterial: new this.Cesium.PolylineGlowMaterialProperty({
                        // eslint-disable-next-line new-cap
                        color: this.Cesium.Color.WHEAT
                    }),
                    clampToGround: true
                }
            })
        },
        //空间线
        drawPolylineSpace(positions) {
            let viewer = this.viewer
            if (positions.length < 1) return
            viewer.entities.add({
                name: '测量点',
                polyline: {
                    positions: positions,
                    width: 5.0,
                    material: new this.Cesium.PolylineGlowMaterialProperty({
                        // eslint-disable-next-line new-cap
                        color: this.Cesium.Color.WHEAT
                    }),
                    depthFailMaterial: new this.Cesium.PolylineGlowMaterialProperty({
                        // eslint-disable-next-line new-cap
                        color: this.Cesium.Color.WHEAT
                    }),
                    clampToGround: false
                }
            })
        },
        //画广告牌
        drawPointLabel(position, pointNum) {
            let viewer = this.viewer
            let Cesium = this.Cesium
            // 本质上就是添加一个点的实体
            return viewer.entities.add({
                name: '测量点',
                position: position,
                point: {
                    color: Cesium.Color.WHEAT,
                    pixelSize: 5,
                    outlineWidth: 3,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY, //
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND // 规定贴地
                },
                label: {
                    text: pointNum,
                    font: '30px sans-serif',
                    fillColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    backgroundColor: Cesium.Color.BLACK,
                    showBackground: true,
                    style: Cesium.LabelStyle.FILL,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                }
            })
        },
        // 方向
        Bearing(from, to) {
            let Cesium = this.Cesium
            let fromCartographic = Cesium.Cartographic.fromCartesian(from)
            let toCartographic = Cesium.Cartographic.fromCartesian(to)
            let lat1 = fromCartographic.latitude
            let lon1 = fromCartographic.longitude
            let lat2 = toCartographic.latitude
            let lon2 = toCartographic.longitude
            let angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2))
            if (angle < 0) {
                angle += Math.PI * 2.0
            }
            return angle
        },
        // 角度
        pointAngle(point1, point2, point3) {
            let bearing21 = this.Bearing(point2, point1)
            let bearing23 = this.Bearing(point2, point3)
            let angle = bearing21 - bearing23
            if (angle < 0) {
                angle += Math.PI * 2.0
            }
            return angle
        },
        /* 计算空间面积 */
        getArea(positions) {
            let res = 0
            for (let i = 0; i < positions.length - 2; i++) {
                let j = (i + 1) % positions.length
                let k = (i + 2) % positions.length
                let totalAngle = this.pointAngle(positions[i], positions[j], positions[k])
                let tempLength1 = this.getLength(positions[j], positions[0])
                let tempLength2 = this.getLength(positions[k], positions[0])
                res += tempLength1 * tempLength2 * Math.sin(totalAngle) / 2
            }
            res = res.toFixed(2)
            // console.log(res)
            res = parseFloat(res)
            // console.log(Math.abs(res))
            return Math.abs(res)
        },
        /* 在最后一个点处添加标签，显示面积 */
        addArea(area, positions) {
            let viewer = this.viewer
            let Cesium = this.Cesium
            return viewer.entities.add({
                name: '测量点',
                position: positions[positions.length - 1],
                label: {
                    text: area + '平方公里',
                    font: '20px sans-serif',
                    fillColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    backgroundColor: Cesium.Color.BLACK,
                    showBackground: true,
                    style: Cesium.LabelStyle.FILL,
                    pixelOffset: new Cesium.Cartesian2(60, -60),
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
            })
        },
        //画面
        drawPolygon(positions) {
            let viewer = this.viewer
            if (positions.length < 2) return
            return viewer.entities.add({
                name: '测量点',
                polygon: {
                    hierarchy: positions,
                    // eslint-disable-next-line new-cap
                    material: new this.Cesium.ColorMaterialProperty(
                        this.Cesium.Color.WHEAT.withAlpha(0.4)
                    )
                }
            })
        },
        drawSpacePolygon(positions) {

            let viewer = this.viewer
            if (positions.length < 2) return
            if (this.terrainValue) {
                return viewer.entities.add({
                    name: '测量点',
                    polygon: {
                        hierarchy: positions,
                        // eslint-disable-next-line new-cap
                        // perPositionHeight:true,
                        material: new this.Cesium.ColorMaterialProperty(
                            this.Cesium.Color.WHEAT.withAlpha(0.4)
                        ),
                        clampToGround: false
                    }
                })
            } else {
                return viewer.entities.add({
                    name: '测量点',
                    polygon: {
                        hierarchy: positions,
                        // eslint-disable-next-line new-cap
                        perPositionHeight: true,
                        material: new this.Cesium.ColorMaterialProperty(
                            this.Cesium.Color.WHEAT.withAlpha(0.4)
                        ),
                        clampToGround: false
                    }
                })
            }

        },
        //清除测量点位
        clearAllDrawn() {
            let viewer = this.viewer
            this.tempEntities = []
            let entitiesList = viewer.entities._entities._array
            // console.log(entitiesList.length)
            for (let index = 0; index < 10; index++) {
                entitiesList.forEach((item) => {
                    if (item.name == '测量点') {
                        viewer.entities.remove(viewer.entities.getById(item.id))
                        // console.log('移除了' + item.name)
                    }
                })
            }
        },
        //测量方法
        draw(type) {
            let Cesium = this.Cesium
            let that = this
            let viewer = this.viewer
            // let pointNum = 1
            // console.log(pointNum)
            let tempEntities = this.tempEntities
            let floatingPoint = this.floatingPoint
            let activeShape = this.activeShape
            let position = []
            let tempPoints = []
            let activeShapePoints = []
            // 开启深度检测
            viewer.scene.globe.depthTestAgainstTerrain = true
            // 创建场景的HTML canvas元素
            let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
            switch (type) {
                //空间直线绘制
                case 'PolylineSpace':
                    if (this.jieliuFlag === true) {
                        this.$refs.lineMeasureRef2.style.color = 'rgb(146, 171, 243)'
                        this.jieliuFlag = false
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction(function (click) {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                floatingPoint = that.drawPoint(earthPosition)
                            }
                            // 获取位置信息
                            // 从相机位置创建一条射线，这条射线通过世界中movement.position像素所在的坐标,返回Cartesian3坐标
                            let ray = viewer.camera.getPickRay(click.position)
                            // 找到射线与渲染的地球表面之间的交点。射线必须以世界坐标给出。返回Cartesian3坐标
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            that.pointNum += 1
                            let tempLength = tempPoints.length // 记录点数
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointLength = that.getSpaceLength(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let midPosition = that.getMidpoint(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let pointline = that.drawPolylineSpace([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                // console.log(midPosition)
                                let pointLabel = that.addLabel(midPosition, pointLength)
                                tempEntities.push(pointline) // 保存记录
                                tempEntities.push(pointLabel)
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        // 右键单击结束画线
                        handler.setInputAction((click) => {
                            this.$refs.lineMeasureRef2.style.color = '#ffffff'
                            activeShapePoints.pop()
                            viewer.entities.remove(activeShapePoints)
                            viewer.entities.remove(floatingPoint)
                            tempPoints = [] // 清空点位记录
                            handler.destroy()
                            handler = null
                            floatingPoint = undefined
                            activeShape = undefined
                            activeShapePoints = []
                            this.jieliuFlag = true
                            this.pointNum = 0
                        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
                    }
                    break
                // 绘制线
                case 'Polyline':
                    if (this.jieliuFlag === true) {
                        this.$refs.lineMeasureRef.style.color = 'rgb(146, 171, 243)'
                        this.jieliuFlag = false
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction(function (click) {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                floatingPoint = that.drawPoint(earthPosition)
                            }
                            // 获取位置信息
                            // 从相机位置创建一条射线，这条射线通过世界中movement.position像素所在的坐标,返回Cartesian3坐标
                            let ray = viewer.camera.getPickRay(click.position)
                            // 找到射线与渲染的地球表面之间的交点。射线必须以世界坐标给出。返回Cartesian3坐标
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            that.pointNum += 1
                            let tempLength = tempPoints.length // 记录点数
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointLength = that.getLength(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let midPosition = that.getMidpoint(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let pointline = that.drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                let pointLabel = that.addLabel(midPosition, pointLength)
                                tempEntities.push(pointline) // 保存记录
                                tempEntities.push(pointLabel)
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        // 右键单击结束画线
                        handler.setInputAction((click) => {
                            this.$refs.lineMeasureRef.style.color = '#ffffff'
                            activeShapePoints.pop()
                            viewer.entities.remove(activeShapePoints)
                            viewer.entities.remove(floatingPoint)
                            tempPoints = [] // 清空点位记录
                            handler.destroy()
                            handler = null
                            floatingPoint = undefined
                            activeShape = undefined
                            activeShapePoints = []
                            this.jieliuFlag = true
                            this.pointNum = 0
                        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
                    }
                    break
                // 绘制面
                case 'Polygon':
                    if (this.jieliuFlag == true) {
                        this.jieliuFlag = false
                        this.$refs.polygonRef.style.color = 'rgb(146, 171, 243)'
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction(function (click) {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                if (activeShapePoints.length === 0) {
                                    floatingPoint = that.drawPoint(earthPosition)
                                    activeShapePoints.push(earthPosition)
                                    const dynamicPositions = new Cesium.CallbackProperty(function () {
                                        return new Cesium.PolygonHierarchy(activeShapePoints)
                                    }, false)
                                    // console.log(dynamicPositions)
                                    activeShape = that.drawSpacePolygon(dynamicPositions)
                                }
                                activeShapePoints.push(earthPosition)
                            }
                            // 获取位置信息
                            let ray = viewer.camera.getPickRay(click.position)
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            let tempLength = tempPoints.length // 记录点数
                            that.pointNum += 1
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointline = that.drawPolylineSpace([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                tempEntities.push(pointline) // 保存记录
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        // 右键单击结束画面
                        handler.setInputAction((click) => {
                            // 选择一个椭球或地图
                            let cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
                            if (cartesian) {
                                let tempLength = tempPoints.length
                                if (tempLength < 3) {
                                    alert('闭合操作需要至少3个点嗷')
                                } else {
                                    // 闭合最后一条线
                                    let pointline = that.drawPolylineSpace([tempPoints[0], tempPoints[tempPoints.length - 1]])
                                    tempEntities.push(pointline)
                                    that.drawSpacePolygon(tempPoints)
                                    let pointArea = that.getArea(tempPoints)
                                    that.addArea(JSON.stringify(pointArea), tempPoints)
                                    tempEntities.push(tempPoints)
                                    handler.destroy()
                                    handler = null
                                    this.$refs.polygonRef.style.color = '#ffffff'
                                }
                            }
                            activeShapePoints.pop()
                            viewer.entities.remove(activeShapePoints)
                            viewer.entities.remove(floatingPoint)
                            floatingPoint = undefined
                            activeShapePoints = []
                            this.pointNum = 0
                            this.jieliuFlag = true
                        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
                    }
                    break
                // 绘制角
                case 'Angle':
                    if (this.jieliuFlag == true) {
                        this.jieliuFlag = false
                        this.$refs.angleRef.style.color = 'rgb(146, 171, 243)'
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction((click) => {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                if (activeShapePoints.length === 0) {
                                    floatingPoint = that.drawPoint(earthPosition)
                                    activeShapePoints.push(earthPosition)
                                }
                                activeShapePoints.push(earthPosition)
                            }
                            // 获取位置信息
                            let ray = viewer.camera.getPickRay(click.position)
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            let tempLength = tempPoints.length // 记录点数
                            that.pointNum += 1
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointline = that.drawPolylineSpace([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                tempEntities.push(pointline) // 保存记录
                            }
                            if (tempLength == 3) {
                                // 选择一个椭球或地图
                                let cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
                                if (cartesian) {
                                    let tempLength = tempPoints.length
                                    if (tempLength < 3) {
                                        alert('操作需要至少3个点嗷')
                                    } else if (tempLength == 3) {
                                        // 闭合最后一条线
                                        // let pointline = that.drawPolylineSpace([tempPoints[0], tempPoints[tempPoints.length - 1]])
                                        // tempEntities.push(pointline)
                                        // that.drawPolygon(tempPoints)

                                        //利用余弦定理 cosB = (a*a + c*c - b*b) / 2 * ac
                                        let a = this.getSpaceLength(tempPoints[1], tempPoints[2]) * 1000
                                        let b = this.getSpaceLength(tempPoints[0], tempPoints[2]) * 1000
                                        let c = this.getSpaceLength(tempPoints[0], tempPoints[1]) * 1000
                                        let top = Math.pow(a, 2) + Math.pow(c, 2) - Math.pow(b, 2)
                                        let bottom = 2 * a * c
                                        let cosB = top / bottom
                                        //反三角函数
                                        var angle = Math.round(Math.acos(cosB) * 180 / Math.PI)
                                        // console.log(angle)
                                        viewer.entities.add({
                                            name: '测量点',
                                            position: tempPoints[tempPoints.length - 1],
                                            label: {
                                                text: angle + '度',
                                                font: '20px sans-serif',
                                                fillColor: Cesium.Color.WHITE,
                                                outlineWidth: 2,
                                                backgroundColor: Cesium.Color.BLACK,
                                                showBackground: true,
                                                style: Cesium.LabelStyle.FILL,
                                                pixelOffset: new Cesium.Cartesian2(60, -60),
                                                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                                                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                                                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                                                disableDepthTestDistance: Number.POSITIVE_INFINITY
                                            }
                                        })
                                        this.$refs.angleRef.style.color = '#ffffff'
                                        tempEntities.push(tempPoints)
                                        handler.destroy()
                                        handler = null
                                        // console.log(viewer.entities._entities._array)
                                        activeShapePoints.pop()
                                        viewer.entities.remove(activeShapePoints)
                                        viewer.entities.remove(floatingPoint)
                                        floatingPoint = undefined
                                        activeShapePoints = []
                                        this.pointNum = 0
                                        this.jieliuFlag = true
                                    }
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                    }
                    break
                //剖面分析
                case 'Profile':
                    if (this.jieliuFlag === true) {
                        this.$refs.profileRef.style.color = 'rgb(146, 171, 243)'
                        this.jieliuFlag = false
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction((click) => {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                floatingPoint = that.drawPoint(earthPosition)
                            }
                            // 获取位置信息
                            // 从相机位置创建一条射线，这条射线通过世界中movement.position像素所在的坐标,返回Cartesian3坐标
                            let ray = viewer.camera.getPickRay(click.position)
                            // 找到射线与渲染的地球表面之间的交点。射线必须以世界坐标给出。返回Cartesian3坐标
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            that.pointNum += 1
                            let tempLength = tempPoints.length // 记录点数
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointLength = that.getLength(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let midPosition = that.getMidpoint(tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1])
                                let pointline = that.drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                let pointLabel = that.addLabel(midPosition, pointLength)
                                tempEntities.push(pointline) // 保存记录
                                tempEntities.push(pointLabel)
                                this.poumianArray1.push(tempPoints[tempPoints.length - 2])
                                this.poumianArray1.push(tempPoints[tempPoints.length - 1])
                                for (let i = 0; i < 5; i++) {
                                    this.profileloop()
                                }
                                // for (let i = 0; i < this.poumianArray1.length; i++) {
                                //     this.poumianArray1[i]
                                // }
                                let heightarr = []
                                let newHeightarr = []
                                // let startPoint = Cesium.Cartographic.fromCartesian(tempPoints[tempPoints.length - 2])
                                // let endPoint = Cesium.Cartographic.fromCartesian(tempPoints[tempPoints.length - 1])
                                // let geodesic = new Cesium.EllipsoidGeodesic()
                                // geodesic.setEndPoints(startPoint, endPoint)
                                // this.poumianArray1 = geodesic.interpolateUsingFraction(0.1)
                                // console.log(this.poumianArray1)
                                for (let i in this.poumianArray1) {
                                    let categary = Cesium.Cartographic.fromCartesian(this.poumianArray1[i]);
                                    let height = viewer.scene.globe.getHeight(categary)
                                    heightarr.push((height).toFixed(2))
                                }
                                this.profilechart(heightarr)
                                this.$refs.profileboxRef.style.display = 'block'
                                this.$refs.profileRef.style.color = '#ffffff'
                                activeShapePoints.pop()
                                viewer.entities.remove(activeShapePoints)
                                viewer.entities.remove(floatingPoint)
                                tempPoints = [] // 清空点位记录
                                handler.destroy()
                                handler = null
                                floatingPoint = undefined
                                activeShape = undefined
                                activeShapePoints = []
                                this.jieliuFlag = true
                                this.pointNum = 0
                                this.poumianArray1 = []
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        // 右键单击结束画线
                        // handler.setInputAction((click) => {
                        //     this.$refs.profileRef.style.color = '#ffffff'
                        //     activeShapePoints.pop()
                        //     viewer.entities.remove(activeShapePoints)
                        //     viewer.entities.remove(floatingPoint)
                        //     tempPoints = [] // 清空点位记录
                        //     handler.destroy()
                        //     handler = null
                        //     floatingPoint = undefined
                        //     activeShape = undefined
                        //     activeShapePoints = []
                        //     this.jieliuFlag = true
                        //     this.pointNum = 0
                        //     this.poumianArray1 = []
                        // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
                    }
                    break
                //淹没分析
                case 'Water':
                    if (this.jieliuFlag == true) {
                        this.jieliuFlag = false
                        this.$refs.darwWaterRef.style.color = 'rgb(146, 171, 243)'
                        // 取消鼠标双击事件
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                        // 监听鼠标移动
                        handler.setInputAction(function (movement) {
                            if (Cesium.defined(floatingPoint)) {
                                let newPosition = viewer.scene.pickPosition(movement.endPosition)
                                if (Cesium.defined(newPosition)) {
                                    floatingPoint.position.setValue(newPosition)
                                    activeShapePoints.pop()
                                    activeShapePoints.push(newPosition)
                                }
                            }
                        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                        // 左键单击开始画线
                        handler.setInputAction((click) => {
                            let earthPosition = viewer.scene.pickPosition(click.position)
                            if (Cesium.defined(earthPosition)) {
                                if (activeShapePoints.length === 0) {
                                    floatingPoint = that.drawPoint(earthPosition)
                                    activeShapePoints.push(earthPosition)
                                    const dynamicPositions = new Cesium.CallbackProperty(function () {
                                        return new Cesium.PolygonHierarchy(activeShapePoints)
                                    }, false)
                                    activeShape = that.drawPolygon(dynamicPositions)
                                }
                                activeShapePoints.push(earthPosition)
                            }
                            // 获取位置信息
                            let ray = viewer.camera.getPickRay(click.position)
                            position = viewer.scene.globe.pick(ray, viewer.scene)
                            tempPoints.push(position) // 记录点位
                            let tempLength = tempPoints.length // 记录点数
                            that.pointNum += 1
                            // 调用绘制点的接口
                            let point = that.drawPointLabel(tempPoints[tempPoints.length - 1], JSON.stringify(that.pointNum))
                            tempEntities.push(point)
                            // 存在超过一个点时
                            if (tempLength > 1) {
                                // 绘制线
                                let pointline = that.drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]])
                                tempEntities.push(pointline) // 保存记录
                            }
                            if (tempLength == 4) {
                                let cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
                                if (cartesian) {
                                    // 闭合最后一条线
                                    let pointline = that.drawPolyline([tempPoints[0], tempPoints[tempPoints.length - 1]])

                                    const loading = this.$loading({
                                        lock: true,
                                        text: '正在计算高程极值......',
                                        spinner: 'el-icon-loading',
                                        background: 'rgba(0, 0, 0, 0.7)'
                                    });

                                    setTimeout(() => { // 以服务的方式调用的 Loading 需要异步关闭
                                        //求第一条线上的33个点
                                        this.waterArray1.push(tempPoints[0])
                                        this.waterArray1.push(tempPoints[1])
                                        for (let i = 0; i < 5; i++) {
                                            this.waterArray2 = []
                                            for (let i in this.waterArray1) {
                                                if (i == this.waterArray1.length - 1) {
                                                    this.waterArray2.push(this.waterArray1[i])
                                                } else {
                                                    let midpoint = this.getMidpoint(this.waterArray1[i], this.waterArray1[i * 1 + 1])
                                                    this.waterArray2.push(this.waterArray1[i])
                                                    this.waterArray2.push(midpoint)
                                                }
                                            }
                                            this.waterArray1 = this.waterArray2
                                        }
                                        let pointOnline1 = this.waterArray1
                                        this.waterArray1 = []

                                        //求平行线上的33个点
                                        this.waterArray1.push(tempPoints[3])
                                        this.waterArray1.push(tempPoints[2])
                                        for (let i = 0; i < 5; i++) {
                                            this.waterArray2 = []
                                            for (let i in this.waterArray1) {
                                                if (i == this.waterArray1.length - 1) {
                                                    this.waterArray2.push(this.waterArray1[i])
                                                } else {
                                                    let midpoint = this.getMidpoint(this.waterArray1[i], this.waterArray1[i * 1 + 1])
                                                    this.waterArray2.push(this.waterArray1[i])
                                                    this.waterArray2.push(midpoint)
                                                }
                                            }
                                            this.waterArray1 = this.waterArray2
                                        }
                                        let pointOnline2 = this.waterArray1
                                        let heightarr = []
                                        let threeDarr = []
                                        //33*33矩阵
                                        // let matrix = []
                                        for (let i = 0; i < pointOnline1.length; i++) {
                                            this.waterArray1 = []
                                            this.waterArray1.push(pointOnline1[i])
                                            this.waterArray1.push(pointOnline2[i])
                                            for (let j = 0; j < 5; j++) {
                                                this.waterArray2 = []
                                                for (let i in this.waterArray1) {
                                                    if (i == this.waterArray1.length - 1) {
                                                        this.waterArray2.push(this.waterArray1[i])
                                                    } else {
                                                        let midpoint = this.getMidpoint(this.waterArray1[i], this.waterArray1[i * 1 + 1])
                                                        this.waterArray2.push(this.waterArray1[i])
                                                        this.waterArray2.push(midpoint)
                                                    }
                                                }
                                                // this.waterArray1 = this.waterArray2
                                                for (let j in this.waterArray2) {
                                                    let categary = Cesium.Cartographic.fromCartesian(this.waterArray2[j]);
                                                    let height = (viewer.scene.globe.getHeight(categary)).toFixed(2)
                                                    heightarr.push(Number(height))
                                                    let arr = []
                                                    arr.push(height)
                                                    threeDarr.push(arr)
                                                }
                                            }
                                            // matrix.push(this.waterArray1)
                                        }
                                        console.log(threeDarr);
                                        this.profile3DChart(threeDarr)
                                        this.$refs.profileboxRef.style.display = 'block'
                                        this.$refs.profileRef.style.color = '#ffffff'
                                        //解析矩阵求所有点位高度
                                        // let heightarr = [] 
                                        // for (let i in matrix) {
                                        //     let matrix1 = matrix[i]
                                        //     for (let j in matrix1) {
                                        //         let categary = Cesium.Cartographic.fromCartesian(matrix1[j]);
                                        //         let height = (viewer.scene.globe.getHeight(categary)).toFixed(2)
                                        //         heightarr.push(Number(height))
                                        //     }
                                        // }
                                        this.maxWaterHeight = Math.max(...heightarr)
                                        this.minWaterHeight = Math.min(...heightarr)
                                        loading.close();
                                    }, 1000);
                                    tempEntities.push(pointline)
                                    that.drawPolygon(tempPoints)
                                    tempEntities.push(tempPoints)
                                    this.waterArea = tempPoints
                                    handler.destroy()
                                    handler = null
                                    this.$refs.darwWaterRef.style.color = '#ffffff'
                                }
                                activeShapePoints.pop()
                                viewer.entities.remove(activeShapePoints)
                                viewer.entities.remove(floatingPoint)
                                floatingPoint = undefined
                                activeShapePoints = []
                                this.waterArray1 = []
                                this.waterArray2 = []

                                this.pointNum = 0
                                this.jieliuFlag = true
                            }
                        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                    }
                    break
            }
        },
        //所添加点位的合法性验证
        formatEntitiesInfo(item) {
            if (item.name == '' || item.description == '' || item.type == '' || item.lon == '' || item.lat == '' || item.height == '') {
                alert("请输入完整信息!")
                return false
            } else {
                return true
            }
        },
        //添加点位
        addEntities() {
            let viewer = this.viewer
            let Cesium = this.Cesium
            let addtoken = this.formatEntitiesInfo(this.entitiesInfo)
            let item = this.entitiesInfo
            let entitiesArray = viewer.entities._entities._array
            if (addtoken) {
                this.entitiesCount += 1
                viewer.entities.add({
                    id: this.entitiesCount,
                    name: item.name,
                    description: item.type + ',' + item.description,
                    position: Cesium.Cartesian3.fromDegrees(Number(item.position._value.x), Number(item.position._value.y), Number(item.position._value.z)),
                    point: {
                        color: Cesium.Color.WHEAT,
                        pixelSize: 5,
                        outlineWidth: 3,
                        disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    },
                    label: {
                        text: item.name,
                        font: '30px sans-serif',
                        fillColor: Cesium.Color.WHITE,
                        outlineWidth: 2,
                        backgroundColor: Cesium.Color.BLACK,
                        showBackground: true,
                        style: Cesium.LabelStyle.FILL,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER
                    }
                })
                let items = {
                    id: this.entitiesCount,
                    name: item.name,
                    description: item.type + ',' + item.description,
                    lon: item.position._value.x,
                    lat: item.position._value.y,
                    height: item.position._value.z,
                    type: item.type
                }
                this.entitiesArray.push(items)
                viewer.camera.flyTo({
                    destination: Cesium.Cartesian3.fromDegrees(Number(item.position._value.x), Number(item.position._value.y), Number(item.position._value.z) + 1000)
                })
                this.entitiesInfo = {
                    name: '',
                    position: {
                        _value: {
                            x: '',
                            y: '',
                            z: '',
                        }
                    },
                    description: '',
                    type: '',
                },
                    this.$refs.updateBox.style.display = 'none'
            } else {
                alert('手动添加需输入完整信息')
            }
        },
        //通过点击地图添加
        addEntitiesByClick() {
            let viewer = this.viewer
            let Cesium = this.Cesium
            let item = this.entitiesInfo
            // let floatingPoint = this.floatingPoint
            if (item.name == '' || item.description == '' || item.type == '') {
                alert("点击地图添加请输入名称、描述和类型!")
            } else {
                if (this.jieliuFlag === true) {
                    this.jieliuFlag = false
                    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
                    // 取消鼠标双击事件
                    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
                    this.$refs.clickAddBtn.style.color = 'rgb(146, 171, 243)'
                    // handler.setInputAction(function (movement) {
                    //     if (Cesium.defined(floatingPoint)) {
                    //         let newPosition = viewer.scene.pickPosition(movement.endPosition)
                    //         if (Cesium.defined(newPosition)) {
                    //             floatingPoint.position.setValue(newPosition)
                    //             activeShapePoints.pop()
                    //             activeShapePoints.push(newPosition)
                    //         }
                    //     }
                    // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
                    handler.setInputAction((click) => {
                        this.entitiesCount += 1

                        // let earthPosition = viewer.scene.pickPosition(click.position)
                        // if (Cesium.defined(earthPosition)) {
                        //     floatingPoint = this.drawPoint(earthPosition)
                        // }

                        // 获取位置信息
                        // 从相机位置创建一条射线，这条射线通过世界中movement.position像素所在的坐标,返回Cartesian3坐标
                        let ray = viewer.camera.getPickRay(click.position)
                        // 找到射线与渲染的地球表面之间的交点。射线必须以世界坐标给出。返回Cartesian3坐标
                        let position = viewer.scene.globe.pick(ray, viewer.scene)
                        viewer.entities.add({
                            id: this.entitiesCount,
                            name: item.name,
                            description: item.type + ',' + item.description,
                            position: position,
                            point: {
                                color: Cesium.Color.WHEAT,
                                pixelSize: 5,
                                outlineWidth: 3,
                                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                            },
                            label: {
                                text: item.name,
                                font: '30px sans-serif',
                                fillColor: Cesium.Color.WHITE,
                                outlineWidth: 2,
                                backgroundColor: Cesium.Color.BLACK,
                                showBackground: true,
                                style: Cesium.LabelStyle.FILL,
                                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                                horizontalOrigin: Cesium.HorizontalOrigin.CENTER
                            }
                        })
                        let cartographic = this.Cesium.Ellipsoid.WGS84.cartesianToCartographic(
                            position
                        )
                        let longitude = this.Cesium.Math.toDegrees(
                            cartographic.longitude
                        );
                        let latitude = this.Cesium.Math.toDegrees(
                            cartographic.latitude
                        );
                        let items = {
                            id: this.entitiesCount,
                            name: item.name,
                            description: item.type + ',' + item.description,
                            lon: longitude,
                            lat: latitude,
                            height: cartographic.height,
                            type: item.type
                        }
                        this.entitiesArray.push(items)
                        this.entitiesInfo = {
                            name: '',
                            position: {
                                _value: {
                                    x: '',
                                    y: '',
                                    z: '',
                                }
                            },
                            description: '',
                            type: '',
                        }
                        handler.destroy()
                        handler = null
                        // floatingPoint = undefined
                        this.jieliuFlag = true
                        this.$refs.clickAddBtn.style.color = 'rgb(255, 255, 255)'
                    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
                    this.$refs.updateBox.style.display = 'none'
                    handler.setInputAction((click) => {
                        handler.destroy()
                        handler = null
                        // floatingPoint = undefined
                        this.jieliuFlag = true
                        this.$refs.clickAddBtn.style.color = 'rgb(255, 255, 255)'
                    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
                }
            }
        },
        //分页器
        handleCurrentChange(currentPage) {
            this.currentPage = currentPage
        },
        //在表格对点位进行删除操作
        removeThisRow(index, entity) {
            let viewer = this.viewer
            if (this.$refs.updateBox.style.display == 'none') {
                this.$alert('点位删除后无法恢复，您确认删除吗', '注意：', {
                    confirmButtonText: '确定',
                    type: 'warning'
                }).then(() => {
                    viewer.entities.remove(viewer.entities.getById(entity.id))
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    if (viewer.entities._entities._array.length / this.pageSize == 1 && this.currentPage != 1) {
                        this.currentPage -= 1
                    }
                    this.entitiesArray.splice(index, 1)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        //在表格对点位进行修改操作
        updateThisRow(index, entity) {
            let viewer = this.viewer
            let Cesium = this.Cesium
            // console.log(entity)
            // var cartesian33 = new Cesium.Cartesian3(entity.position._value.x, entity.position._value.y, entity.position._value.z);
            // var cartographic = Cesium.Cartographic.fromCartesian(cartesian33);
            // var lat = Cesium.Math.toDegrees(cartographic.latitude);
            // var lon = Math.round(Cesium.Math.toDegrees(cartographic.longitude));
            // var height = Math.round(cartographic.height);
            // console.log(lat,lon,height)
            // let data = Cesium.Ellipsoid.WGS84.cartesianToCartographic(entity.position._value.x, entity.position._value.y, entity.position._value.z)
            var newdescription1 = entity.description + ''
            var newdescription2 = entity.description + ''
            if (entity.description.length > 5) {
                newdescription1 = newdescription1.substr(5, entity.description.length - 5)
            }
            var type = newdescription2.substr(0, 4)
            // console.log(type)
            this.entitiesInfo1 = {
                id: entity.id,
                name: entity.name,
                position: {
                    _value: {
                        x: entity.lon,
                        y: entity.lat,
                        z: entity.height,
                    }
                },
                description: newdescription1,
                type: type,
            }
            this.$refs.updateBox.style.display = 'block'
        },
        //点位更新
        updateEntities() {
            let viewer = this.viewer
            let Cesium = this.Cesium
            let item = this.entitiesInfo1
            let items = {
                id: item.id,
                name: item.name,
                description: item.type + ',' + item.description,
                lon: item.position._value.x,
                lat: item.position._value.y,
                height: item.position._value.z
            }
            let addtoken = this.formatEntitiesInfo(this.entitiesInfo1)
            if (addtoken) {
                viewer.entities.remove(viewer.entities.getById(item.id))
                viewer.entities.add({
                    id: item.id,
                    name: item.name,
                    description: item.type + ',' + item.description,
                    position: Cesium.Cartesian3.fromDegrees(Number(item.position._value.x), Number(item.position._value.y), Number(item.position._value.z)),
                    point: {
                        color: Cesium.Color.WHEAT,
                        pixelSize: 5,
                        outlineWidth: 3,
                        disableDepthTestDistance: Number.POSITIVE_INFINITY, //
                    },
                    label: {
                        text: item.name,
                        font: '30px sans-serif',
                        fillColor: Cesium.Color.WHITE,
                        outlineWidth: 2,
                        backgroundColor: Cesium.Color.BLACK,
                        showBackground: true,
                        style: Cesium.LabelStyle.FILL,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER
                    }
                })
            }
            let arr = this.entitiesArray
            for (let i in arr) {
                if (arr[i].id == item.id) {
                    arr.splice(i, 1)
                }
            }
            arr.push(items)

            this.$refs.updateBox.style.display = 'none'
        },
        //获取中点高度
        getMidHeight(start, end) {
            let Cesium = this.Cesium
            let viewer = this.viewer
            let startPoint = Cesium.Cartographic.fromCartesian(start)
            let endPoint = Cesium.Cartographic.fromCartesian(end)
            let geodesic = new Cesium.EllipsoidGeodesic()
            geodesic.setEndPoints(startPoint, endPoint)
            let geoPoint = geodesic.interpolateUsingSurfaceDistance(0.5)
            let height = viewer.scene.globe.getHeight(geoPoint)
            // console.log("中点位置：" + height)
            return height
        },
        //剖面分析循环取中点
        profileloop() {
            this.poumianArray2 = []
            for (let i in this.poumianArray1) {
                if (i == this.poumianArray1.length - 1) {
                    this.poumianArray2.push(this.poumianArray1[i])
                } else {
                    let midpoint = this.getMidpoint(this.poumianArray1[i], this.poumianArray1[i * 1 + 1])
                    this.poumianArray2.push(this.poumianArray1[i])
                    this.poumianArray2.push(midpoint)
                }
            }
            this.poumianArray1 = this.poumianArray2
        },
        //剖面分析的表格加载
        profilechart(heightarr) {
            let myEchart = this.$echarts.init(document.getElementById("profile"))
            let option = {
                xAxis: {
                    type: 'category',
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#fff",
                            width: 1,
                            type: "solid"
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: "#fff",
                            width: 1,
                            type: "solid"
                        }
                    },
                    axisLabel: {//y轴文字的配置
                        textStyle: {
                            color: "#fff",
                            margin: 15
                        },
                    }
                },
                yAxis: {
                    minInterval: 500,
                    scale: true,
                    type: 'value',
                    splitLine: {
                        show: true
                    },
                    name: "单位：米",//y轴上方的单位
                    nameTextStyle: {//y轴上方单位的颜色
                        color: '#fff'
                    },
                    axisLabel: {//y轴文字的配置
                        textStyle: {
                            color: "#fff",
                            margin: 15
                        },
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'line'
                    },
                },
                series: [
                    {
                        data: heightarr,
                        type: 'line',
                        symbol: 'none',
                        smooth: true,
                        areaStyle: {
                            opacity: 0.8,
                            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: 'rgb(128, 255, 165)'
                                },
                                {
                                    offset: 1,
                                    color: 'rgb(1, 191, 236)'
                                }
                            ])
                        }
                    }
                ]
            }
            myEchart.setOption(option)
        },
        profile3DChart(heightarr) {
            let myEchart = this.$echarts.init(document.getElementById("profile"))
            let option = {
                tooltip: {},
                xAxis3D: {
                    name: "x",  //x轴显示为x
                    type: 'value',
                    // min: 'dataMin',//获取数据中的最值
                    // max: 'dataMax'
                    axisTick: {
                        show: false, //显示每个值对应的刻度
                    },
                    axisLine: {     //x轴坐标轴，false为隐藏，true为显示
                        show: true
                    },
                    axisLabel: {
                        show: false    ////是否显示刻度 (刻度上的数字，或者类目)， false为隐藏，true为显示
                    },
                    itemStyle: {
                        borderColor: "#fff",
                        backgroundColor: "#fff"
                    },
                },
                yAxis3D: {
                    name: "y",//y轴显示为y
                    type: 'value',
                    splitNumber: 5,
                    axisTick: {
                        show: false, //显示每个值对应的刻度
                    },
                },
                zAxis3D: {
                    name: "z",//z轴显示为z
                    type: 'value',
                    axisTick: {
                        show: false, //显示每个值对应的刻度
                    },
                },
                grid3D: {
                    axisLine: {
                        lineStyle: {//坐标轴样式
                            color: '#070707',//轴线颜色
                            opacity: .8,//(单个刻度不会受影响)
                            width: 1//线条宽度
                        }
                    },
                    axisPointer: {
                        lineStyle: {
                            color: '#f00'//坐标轴指示线
                        },
                        show: false//不坐标轴指示线
                    },
                    viewControl: {
                        // autoRotate: true,//旋转展示
                        // projection: 'orthographic'
                        // beta:0,
                        distance: 230, //与视角的距离，值越大，图离视角越远，图越小
                        alpha: 7, //绕x轴旋转的角度（上下旋转），增大，视角顺时针增大（向上）
                        beta: 20, //绕y轴旋转的角度（左右旋转），增大，视角逆时针增大（向右）
                        center: [-15, -5, -20]  //第一个参数：增大，视角沿x轴正方向水平右移动（图向左）；第二个参数：增大，视角沿y轴正方向垂直向上移动（图向下）；第三个参数：增大，视角向z轴正方向移动（图变小）
                    },
                    
                },

                series: [{
                    type: 'scatter3D',
                    dimensions: ['x', 'y', 'z'//悬浮到点时弹出的显示框信息
                    ],
                    // encode: {
                    // x: [3, 1, 5],      // 表示维度 3、1、5 映射到 x 轴。
                    // y: 1,              // 表示维度 2 映射到 y 轴。
                    // z: 3,
                    // tooltip:['a','c','b'], // 表示维度 3、2、4 会在 tooltip 中显示。
                    // label: 'a'           // 表示 label 使用维度 3。
                    // },
                    data: heightarr,
                    symbolSize: 4,//点的大小
                    // symbol: 'triangle',
                    itemStyle: {
                        // borderWidth: 1,
                        color: "#87f0e5",
                        // borderColor: 'rgba(255,255,255,0.8)'//边框样式
                    },
                    emphasis: {
                        itemStyle: {
                            color: '#ccc'//高亮
                        }
                    },
                    // itemStyle: {
                    //     color: "#87f0e5"
                    // }
                }],
                backgroundColor: "#e8e8e8"
            };
            myEchart.setOption(option)
        },
        //开始淹没分析
        waterAnalysis(targetHeight1, positions, waterHeight1) {
            this.$refs.waterComing.style.color = 'rgb(146, 171, 243)'
            let viewer = this.viewer
            let Cesium = this.Cesium
            let targetHeight = targetHeight1 * 1
            let waterHeight = waterHeight1 * 1
            // console.log(positions)
            let adapCoordi = []
            positions.forEach((item) => {
                let cartographic = this.Cesium.Ellipsoid.WGS84.cartesianToCartographic(item)
                let lon = this.Cesium.Math.toDegrees(cartographic.longitude)
                let lat = this.Cesium.Math.toDegrees(cartographic.latitude)
                let arr = Cesium.Cartesian3.fromDegrees(lon, lat, 0)
                adapCoordi.push(arr)
            })
            // console.log(adapCoordi)
            let entity = viewer.entities.add({
                name: '测量点',
                polygon: {
                    hierarchy: adapCoordi,
                    perPositionHeight: true,
                    extrudedHeight: new Cesium.CallbackProperty(() => {
                        waterHeight += 3;
                        if (waterHeight > targetHeight) {
                            waterHeight = targetHeight;
                            this.$refs.waterComing.style.color = '#ffffff'
                        }
                        return waterHeight
                    }, false),
                    material: new Cesium.Color.fromBytes(0, 191, 255, 100),
                }
            });

        },
        //重置淹没分析
        resetWater() {
            let viewer = this.viewer
            this.maxWaterHeight = 0
            this.minWaterHeight = 0
            this.clearAllDrawn()
            this.waterArea = []
            // viewer.entities._entities._array.forEach((item) => {
            //     if (item._id.length == 36) {
            //         viewer.entities.remove(viewer.entities.getById(item._id))
            //     }
            // })
        }
    },
    mounted() {
        this.init()
        this.mouseMoveInfo()
        this.initEntities()
    }
}
</script>

<style>
/* .dv-border-svg-container>polygon:nth-child(1), */
.dv-border-svg-container>polygon:nth-child(14),
.dv-border-svg-container>polygon:nth-child(15),
.dv-border-svg-container>polyline {
    display: none;
}

.cesium-widget-credits {
    display: none !important;
    color: rgb(99, 91, 80);
}

#projectTitle {
    line-height: 61px;
    color: rgb(146, 171, 243);
    text-shadow: 0 0 10px rgb(146, 171, 243), 0 0 20px rgb(146, 171, 243), 0 0 30px rgb(146, 171, 243), 0 0 40px rgb(146, 171, 243);
}

.home-btn-style {
    width: 38px;
    height: 38px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 50%;
    position: absolute;
    z-index: 100;
    cursor: pointer;
}

.dateAndWeather {
    width: 150px;
    height: 38px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    position: absolute;
    top: 10px;
    left: 190px;
    z-index: 99;
    border-radius: 20px;
}

.headerDate {
    width: 100px;
    font-size: smaller;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 99;
}

.icon-font {
    width: 30px;
    height: 30px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.search_box {
    width: 200px;
    height: 38px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    color: white;
    position: absolute;
    right: 80px;
    top: 10px;
    z-index: 100;
    cursor: pointer;
}

.bottomInfo_box {
    width: 1100px;
    height: 38px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    color: white;
    position: absolute;
    transform: translate(50%, 0);
    z-index: 100;
    cursor: pointer;
}

.bottomInfo_box>div {
    float: left;
    font-size: small;
    margin-left: 28px;
}

input::-webkit-input-placeholder {
    /* WebKit browsers */
    color: white;
}

input:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: white;
}

input::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: white;
}

input:-ms-input-placeholder {
    /* Internet Explorer 10+ */
    color: white;
}

#echart_box {
    width: 800px;
    height: 400px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 10px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    display: none;
}

#echart {
    width: 700px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
    display: none;
}

.util_box {
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    color: white;
    position: absolute;
    z-index: 100;
    cursor: pointer;
}

.addEntities_box {
    width: 200px;
    height: 300px;
    left: 10px;
    top: 160px;
    font-size: small;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    color: white;
    position: absolute;
    z-index: 100;
    display: none;
}

.input_style {
    width: 100px;
    height: 16px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    color: white;
    z-index: 100;
    cursor: pointer;
}

.add_style {
    width: 80px;
    height: 30px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    line-height: 30px;
    text-align: center;
    border-radius: 10px;
    font-size: small;
    cursor: pointer;
    position: absolute;
    /* left: 50%;
    top: 250px;
    transform: translate(-50%, 0); */
}

.entitiesInfoBox {
    width: 900px;
    height: 500px;
    background-color: white;
    color: rgb(146, 171, 243);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 10px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 110;
    display: none;
}

.tableUtilBtn {
    background-color: rgb(146, 171, 243);
    color: white;
    width: 40px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    margin-top: 5px;
    border-radius: 5px;
    cursor: pointer;
}

#profile_box {
    width: 800px;
    height: 350px;
    background-color: rgba(39, 52, 125, 0.7);
    border: 1px solid rgb(146, 171, 243);
    text-align: center;
    line-height: 40px;
    border-radius: 10px;
    position: absolute;
    left: 50%;
    top: 70%;
    transform: translate(-50%, -50%);
    z-index: 100;
    display: none;
}

#profile {
    width: 700px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
}

.darwWaterBtn {
    border: 1px solid rgb(146, 171, 243);
    height: 30px;
    width: 100px;
    line-height: 30px;
    border-radius: 5px;
    background-color: rgb(39, 52, 125);
    margin: 0 auto;
    margin-top: 10px;
}

.scale {
    border: 1px solid rgb(146, 171, 243);
    height: 30px;
    width: 150px;
    line-height: 30px;
    font-size: small;
    background-color: rgba(39, 52, 125, 0.7);
    position: absolute;
    left: 5px;
    bottom: 5px;
    z-index: 100;
    border-radius: 10px;
}
</style>